package com.shop.socket.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * @author Song Yinghui
 * @date 2019/12/13
 * @Version 1.0
 *
 *  基于 TCP协议的 socket 编程
 */
public class ServeSocket {

    public void start() throws IOException {
        int port = 5555;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("wait for connect ...");
        //accept() 一直阻塞到有连接进来,拿到那个连接
        while (true) {
            Socket socket = serverSocket.accept();

            System.out.println("this is a connect ..."+" source port : "+socket.getPort()+"\t"+ socket.getInetAddress().getHostAddress());
            InputStream inputStream = socket.getInputStream();
            StringBuilder stringBuilder = new StringBuilder();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuilder.append(new String(buffer, 0, len, Charset.forName("utf-8")));
            }
            System.out.println("the client send message is: " + stringBuilder.toString());

            OutputStream outputStream = socket.getOutputStream();
            String str = "I'm socket server, I received you send message ,so this is my ans";
            outputStream.write(str.getBytes("UTF-8"));

            outputStream.close();
            inputStream.close();
        }
    }

    public static void main(String[] args) throws IOException {
        new ServeSocket().start();
    }
}
